package com.gmcloud.common.datasource;

import com.baomidou.dynamic.datasource.processor.DsProcessor;
import com.baomidou.dynamic.datasource.provider.DynamicDataSourceProvider;
import com.gmcloud.common.datasource.config.DataSourceProperties;
import com.gmcloud.common.datasource.config.JdbcDynamicDataSourceProvider;
import com.gmcloud.common.datasource.config.LastParamDsProcessor;
import org.jasypt.encryption.StringEncryptor;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author zl.sir
 * @version 1.0
 * @since 2022/8/23 17:50
 * 动态数据源切换配置
 */
@Configuration(proxyBeanMethods = false)
@AutoConfigureAfter(DataSourceAutoConfiguration.class)
@EnableConfigurationProperties(DataSourceProperties.class)
public class DynamicDataSourceAutoConfiguration {


    /**
     * 从数据源中获取 配置信息
     * @param stringEncryptor  加密
     * @param properties  数据源配置
     * @return 数据源生产者
     */
    @Bean
    public DynamicDataSourceProvider dynamicDataSourceProvider(StringEncryptor stringEncryptor,
                                                               DataSourceProperties properties) {
        return new JdbcDynamicDataSourceProvider(stringEncryptor, properties);
    }


    @Bean
    public DsProcessor dsProcessor() {
        return new LastParamDsProcessor();
    }
}
